import { Express, Request, Response } from "express";
import {
  readLoiginData,
  readRegisterData,
  getUserList,
  delUser,
  updateUser,
} from "../model/users";
import { Users } from "../tool/varType";
import { tokenKey } from "../config/config";
const jwt = require("jsonwebtoken");
export default function (app: Express) {
  // 登录接口
  app.post("/api/login", async function (req: Request, res: Response) {
    const user: Users = req.body;
    const { success, data } = await readLoiginData(user);
    if (!success) {
      res.json({ success: false, msg: "用户名或密码错误" });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: "用户名或密码错误" });
      return;
    }
    /**
     * 获取token
     * jwt.sign({对象},密钥,有效期)
     */
    const token = jwt.sign({ id: data[0].id }, tokenKey, {
      expiresIn: 24 * 60 * 60,
    });
    res.json({ success: true, token: token, data: data });
  });
  //注册接口
  app.post("/api/register", async function (req: Request, res: Response) {
    const user: Users = req.body;
    const { success, data } = await readRegisterData(user);
    if (!success) {
      res.json({ success: false, msg: data.message });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: data.message });
      return;
    }
    res.json({ success: true, msg: "添加成功" });
  });
  // 获取用户数据列表
  app.get("/api/getUserList", async function (req: Request, res: Response) {
    const { page } = req.query as any;
    const { success, data } = await getUserList(Number(page));
    if (!success) {
      res.json({ success: false, msg: data.message });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: data.message });
      return;
    }
    res.json({ success: true, data, total: data.length });
  });
  // 删除用户
  app.get("/api/deluser", async function (req: Request, res: Response) {
    const { id } = req.query as any;
    const { success, data } = await delUser(id);
    if (!success) {
      res.json({ success: false, msg: data.message });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: data.message });
      return;
    }
    res.json({ success: true, msg: "删除成功" });
  });
  // 更新用户
  app.post("/api/updateUser", async function (req: Request, res: Response) {
    const user: Users = req.body;
    console.log((req as any).uids, "---s");
    // console.log(req);

    const { success, data } = await updateUser(user);
    if (!success) {
      res.json({ success: false, msg: data.message });
      return;
    } else if (data.length == 0) {
      res.json({ success: false, msg: data.message });
      return;
    }
    res.json({ success: true, msg: "更新成功" });
  });
}
